﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
using System.Net.Mail;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

namespace DataAccess
{
    public class ElectrosRepository : ConnectionClass
    {
        public ElectrosRepository() : base() { }

        public IEnumerable<Menu> GetMenu(int roleID)
        {
            return new UserRepository().getUserType(roleID).Menus.AsEnumerable();
        }

        public int RandomGenerator()
        {
            int numericValue = 0;
            for (int i = 0; i < 6; i++)
            {
                Random rnd = new Random();
                numericValue += rnd.Next(0, 9);
            }

            return numericValue;
        }

        public void sendNotificationEmail(string username, string bodyContent, string subject)
        {
            User u = new UserRepository().GetUserByUsername(username);
            MailMessage mm = new MailMessage();
            mm.To.Add(u.Email);
            mm.From = new MailAddress("markmariani21@gmail.com");
            mm.Subject = subject;

            mm.Body = "Dear," + username + ", <br/>" + bodyContent;

            mm.IsBodyHtml = true;
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential("markmariani21@gmail.com", "Abaddon0421091");
            client.Send(mm);
        }

        private byte[] KEY_192;
        private byte[] IV_192; 

        public string DecryptPassword(String vl, string key)
        {
            byte[] pinNumber = Encoding.UTF8.GetBytes(key);
            byte[] KeyWithSecret = new byte[KEY_192.Length + pinNumber.Length];
            Array.Copy(pinNumber, KeyWithSecret, pinNumber.Length);
            Array.Copy(KEY_192, 0, KeyWithSecret, pinNumber.Length, KEY_192.Length);

            if (vl != "")
            { //if
                TripleDESCryptoServiceProvider cryptoprovider = new TripleDESCryptoServiceProvider();
                Byte[] buffer = Convert.FromBase64String(vl);
                MemoryStream ms = new MemoryStream(buffer);
                CryptoStream cs = new CryptoStream(ms, cryptoprovider.CreateDecryptor(KeyWithSecret, IV_192), CryptoStreamMode.Read);
                StreamReader sw = new StreamReader(cs);
                return sw.ReadToEnd();
            } //if
            return "";
        } //decrypt

        public void SendEmail(string email, string username, Fault f)
        {
            string location = CreatePDFFault(f);
            //string barcodeLocation;

            MailMessage mm = new MailMessage();
            mm.To.Add(email);
            mm.From = new MailAddress("markmariani21@gmail.com");
            mm.Subject = "Your Fault Request has been placed! ";
            mm.Attachments.Add(new Attachment(location));
            //mm.Attachments.Add(new Attachment(barcodeLocation));

            mm.Body = "Dear," + username + ", <br/> your fault request has been placed. Thank you.<br/>Date and Time of Request: " + DateTime.Now + "   Fault Id:" + f.ID;

            mm.IsBodyHtml = true;
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential("markmariani21@gmail.com", "Abaddon0421091");
            client.Send(mm);
        }

        public string CreatePDFFault(Fault fault)
        {
            User user = new UserRepository().GetUserByUsername(fault.Username);

            string contents = "";
            Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("C:\\Users\\Owner\\Desktop\\Faults\\"+fault.ID+".pdf", FileMode.Create));
            string Address = user.HouseNo + ", " + user.Street+" "+user.Town+" "+user.Postcode;
            doc.Open();
            contents = "<b>Fault Receipt</b><br/><br/>";
            contents += "<table><tr><td><b>Username:</b>" + user.Username + "</td></tr><tr><td><b>Full Name:</b>" + user.FirstName + " " + user.LastName + "</td></tr><tr><td><b>Address:</b>" + Address +" "+ user.Country.Name + "</td></tr><tr><td><b>Date:</b>" + fault.EnteredDate + "</td></table>";
            contents += "<br/>";
            contents += "<table><b><tr><td>Fault Id</td><td>Product Name</td><td>Fault Description</td></tr></b>";

            Product p = new ProductRepository().GetProductByID(fault.OrderDetail.ProductId_FK);

            contents += "<tr><td>" + fault.ID + "</td><td>" + p.Name + "</td><td>" + fault.Description + "</td></tr>";

            contents += "</table>";

            //Read string contents using stream reader and convert html to parsed conent
            var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);

            //Get each array values from parsed elements and add to the PDF document
            foreach (var htmlElement in parsedHtmlElements)
                doc.Add(htmlElement as IElement);

            doc.Close();

            string location = "C:\\Users\\Owner\\Desktop\\Faults\\" + fault.ID + ".pdf";

            return location;
        }

        /*
        public Image GenereateBarcode()
        {
            byte[] imgbyte = new BarcodeServ.BarCodeSoapClient().Code39(RandomGenerator().ToString(), 10, true, "Userbarcode");
            System.IO.MemoryStream ms = new System.IO.MemoryStream(imgbyte);
            Image img = Image.FromStream(ms);
            return img;
        }
         */
    }
    
}
